/**
 * 以primitive加载gltf
 */
export default class GltfLoaderPrimitive {
  constructor(viewer, Cesium) {
    this.viewer = viewer;
    this.Cesium = Cesium;
    this.primitiveCollection = new this.Cesium.PrimitiveCollection();
    this.viewer.scene.primitives.add(this.primitiveCollection);
    this.model = null;
    this._setInterval = null;//动画
  }


  /**
   * 添加 gltf：params:gltfUrl, scale, lon, lat, height
   * @param option
   */
  addGltfPrimitive(option) {
    try {
      let {gltfUrl, scale, lon, lat, height, id} = option;
      this.removeGltfPrimitive(id);
      let modelMatrix = this.Cesium.Transforms.eastNorthUpToFixedFrame(
      this.Cesium.Cartesian3.fromDegrees(lon, lat, height));
      this.model = this.Cesium.Model.fromGltf({
        id: {id: id},
        url: gltfUrl,
        modelMatrix: modelMatrix,
        distanceDisplayCondition:new this.Cesium.DistanceDisplayCondition(0.0, 1000.0),
        scale: scale    //放大倍数
      });
      this.primitiveCollection.add(this.model);
    } catch (e) {

    }
  }

  /**
   * 根据id移除primitive
   * @param id
   */
  removeGltfPrimitive(id) {
    try {
      let p = this.getGltfById(id);//如果已经存在，则移除重新添加
      if (p) {
        this.primitiveCollection.remove(p);
      }
      this.stopAnimate();
    } catch (e) {

    }
  }

  /**
   * 根据id获取primitive
   * @param id
   * @returns {*}
   */
  getGltfById(id) {
    try {
      let length = this.primitiveCollection.length;
      for (let i = 0; i < length; ++i) {
        let p = this.primitiveCollection.get(i);
        if (p._id.id && p._id.id == id) {
          return p;
        }
      }
      return null;
    } catch (e) {

    }
  }

  /**
   * 返回所有的gltfPrimitive
   */
  getAllGltfPrimitives() {
    try {
      if (this.primitiveCollection) {
        return this.primitiveCollection;
      }
    } catch (e) {

    }
  }

  /**
   * 移除所有的gltf
   */
  removeAllGltfPrimitive() {
    try {
      this.viewer.scene.primitives.remove(this.primitiveCollection);
    } catch (e) {
    }
  }

  /**
   * 旋转矩阵 可以用来做旋转变换
   * @param id
   * @param rotation
   */
  rotateRefresh({id, rotation}) {
    let rotationM;
    let newMatrix4Rotation;//旋转矩阵
    let oldMatrix;//模型矩阵
    let oldCenter;// 模型高度调整前中心点笛卡尔坐标
    let oldCartographic;// 高度调整前的弧度坐标
    let oldCartesian;//c3坐标
    let ps = this.primitiveCollection._primitives;
    try {
      rotationM = this.Cesium.Matrix3.fromRotationZ(this.Cesium.Math.toRadians(rotation)); // fromRotationZ表示水平方向旋转的度数 fromRotationZ
      for (let i = 0; i < ps.length; i++) {
        if (ps[i].id.id == id) {//如果存在该id
          oldMatrix = ps[i].modelMatrix;
          oldCenter = new this.Cesium.Cartesian3(oldMatrix[12], oldMatrix[13], oldMatrix[14]);// 模型高度调整前中心点笛卡尔坐标  4*4矩阵中的平移坐标 x、y、z
          oldCartographic = this.Cesium.Cartographic.fromCartesian(oldCenter);// 高度调整前的弧度坐标
          oldCartesian = this.viewer.scene.globe.ellipsoid.cartographicToCartesian(oldCartographic);
          newMatrix4Rotation = this.Cesium.Matrix4.multiplyByMatrix3(this.Cesium.Transforms.eastNorthUpToFixedFrame(
            oldCartesian), rotationM, new this.Cesium.Matrix4());// 计算矩阵4的变换矩阵（在原变换中，累加变换）
          ps[i].modelMatrix = newMatrix4Rotation;
        }
      }
    } catch (e) {

    }
  }

  /**
   * 平移矩阵动画
   * @param id
   * @param lon  //可选参数默认为当前
   * @param lat  //可选参数，默认为当前
   * @param height
   */
  transRefresh({id, lon, lat, height}) {
    let rotation = 0;
    let rotationM;
    let newMatrix4Trans;//旋转矩阵
    let oldMatrix;//模型矩阵
    let oldCenter;// 模型高度调整前中心点笛卡尔坐标
    let oldCartographic;// 高度调整前的弧度坐标
    let newHeight;
    let newCartographic, headingPitchRoll, newCartesian;
    let ps = this.primitiveCollection._primitives;
    // Cesium.Cartesian3.fromDegrees(112.21214483914957, 29.111113499589408, 100));
    try {
      rotationM = this.Cesium.Matrix3.fromRotationZ(this.Cesium.Math.toRadians(rotation)); // fromRotationZ表示水平方向旋转的度数 fromRotationZ
      for (let i = 0; i < ps.length; i++) {
        if (ps[i].id.id == id) {//如果存在该id
          oldMatrix = ps[i].modelMatrix;
          oldCenter = new this.Cesium.Cartesian3(oldMatrix[12], oldMatrix[13], oldMatrix[14]);// 模型高度调整前中心点笛卡尔坐标  4*4矩阵中的平移坐标 x、y、z
          oldCartographic = this.Cesium.Cartographic.fromCartesian(oldCenter);// 高度调整前的弧度坐标
          // newHeight = oldCartographic.height + height;
          newHeight = height;
          if (lon && lat) {
            newCartesian = this.Cesium.Cartesian3.fromDegrees(lon, lat, newHeight);
          } else {
            newCartographic = new this.Cesium.Cartographic(oldCartographic.longitude, oldCartographic.latitude, newHeight); // 高度调整后的弧度坐标
            newCartesian = this.viewer.scene.globe.ellipsoid.cartographicToCartesian(newCartographic);
          }
          headingPitchRoll = new this.Cesium.HeadingPitchRoll(0, 0, 0);
          //平移变换
          newMatrix4Trans = this.Cesium.Transforms.headingPitchRollToFixedFrame(newCartesian, headingPitchRoll,
            this.Cesium.Ellipsoid.WGS84, this.Cesium.Transforms.eastNorthUpToFixedFrame, new this.Cesium.Matrix4());
          ps[i].modelMatrix = newMatrix4Trans;
        }
      }
    } catch (e) {

    }
  }

  /**
   * 开启动画
   */
  startAnimate({rotationStep, minRalativeHeight, heightSize}) {
    let isRight = true;
    let rotation = 0;
    let rotationM;
    let newMatrix4Trans;//平移矩阵
    let newMatrix4Rotation;//旋转矩阵

    let oldMatrix;
    let oldCenter;// 模型高度调整前中心点笛卡尔坐标
    let oldCartographic;// 高度调整前的弧度坐标
    let newHeight;
    let newCartographic, headingPitchRoll, newCartesian;
    try {
      let ps = this.primitiveCollection._primitives;
      this._setInterval = setInterval(() => {
        if (isRight) {
          rotation += rotationStep;
          if (rotation >= rotationStep * 5) {
            isRight = !isRight;
          }
        } else {
          rotation -= rotationStep;
          if (rotation <= -rotationStep * 5) {
            isRight = !isRight;
          }
        }
        // let translation;
        rotationM = this.Cesium.Matrix3.fromRotationZ(this.Cesium.Math.toRadians(rotation)); // fromRotationZ表示水平方向旋转的度数 fromRotationZ
        for (let i = 0; i < ps.length; i++) {
          oldMatrix = this.primitiveCollection._primitives[i].modelMatrix;
          oldCenter = new this.Cesium.Cartesian3(oldMatrix[12], oldMatrix[13], oldMatrix[14]);// 模型高度调整前中心点笛卡尔坐标  4*4矩阵中的平移坐标 x、y、z
          oldCartographic = this.Cesium.Cartographic.fromCartesian(oldCenter);// 高度调整前的弧度坐标
          // translation =  new this.Cesium.Cartesian3( 0, 0, oldCartographic.height + minRalativeHeight + rotation * heightSize);
          // this.Cesium.Matrix4.multiplyByTranslation(oldMatrix, translation, oldMatrix);
          // console.log(oldCartographic.height);
          // newHeight = oldCartographic.height + minRalativeHeight + rotation * heightSize;
          newHeight =  minRalativeHeight + rotation * heightSize;
          newCartographic = new this.Cesium.Cartographic(oldCartographic.longitude, oldCartographic.latitude, newHeight); // 高度调整后的弧度坐标
          newCartesian = this.viewer.scene.globe.ellipsoid.cartographicToCartesian(newCartographic);
          headingPitchRoll = new this.Cesium.HeadingPitchRoll(0, 0, 0);

          //平移变换
          newMatrix4Trans = this.Cesium.Transforms.headingPitchRollToFixedFrame(newCartesian, headingPitchRoll,
            this.Cesium.Ellipsoid.WGS84, this.Cesium.Transforms.eastNorthUpToFixedFrame, new this.Cesium.Matrix4());
          ps[i].modelMatrix = newMatrix4Trans;

          //旋转变换
          newMatrix4Rotation = this.Cesium.Matrix4.multiplyByMatrix3(this.Cesium.Transforms.eastNorthUpToFixedFrame(
            newCartesian), rotationM, new this.Cesium.Matrix4());// 计算矩阵4的变换矩阵（在原变换中，累加变换）
          ps[i].modelMatrix = newMatrix4Rotation;

          //两个矩阵相乘有哪地方出入导致矩阵变换出错
          // this.primitiveCollection._primitives[i].modelMatrix =this.Cesium.Matrix4.multiply(newMatrix4Trans, newMatrix4Rotation, new this.Cesium.Matrix4());
        }

      }, 200);
    } catch (e) {

    }
  }

  /**
   * 关闭动画
   */
  stopAnimate() {
    if (this._setInterval) {
      clearInterval(this._setInterval);
    }
  }


}
